<template>
  <div class="node-create">
    <!-- 顶部导航 -->
    <div class="custom-header">
      <span class="back-area" @click="goToNodeManagement">
        <svg class="back-icon" viewBox="0 0 16 16" width="18" height="18">
          <path
            d="M10.5 13 6 8l4.5-5"
            stroke="#bfbfbf"
            stroke-width="1.5"
            fill="none"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
        <span class="back-text">返回</span>
      </span>
      <span class="header-divider">|</span>
      <span class="header-title">{{
        isEditMode ? "修改节点" : "新增节点"
      }}</span>
    </div>

    <!-- 表单卡片 -->
    <a-card class="form-card" :bordered="false">
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        class="form"
      >
        <a-form-item label="节点名称" name="nodeName" required>
          <a-input
            v-model:value="formData.nodeName"
            placeholder="请输入节点名称"
            maxlength="20"
            show-count
            size="large"
          />
        </a-form-item>

        <a-form-item label="节点类型" name="nodeType" required>
          <a-select
            v-model:value="formData.nodeType"
            placeholder="请选择节点类型"
            size="large"
            :options="nodeTypeOptions"
          />
        </a-form-item>

        <a-form-item label="责任单位" name="department">
          <div class="select-with-add">
            <a-select
              v-model:value="formData.department"
              placeholder="请选择责任单位"
              size="large"
              show-search
              :options="departmentOptions"
              style="flex: 1"
            />
            <a-button @click="showAddDepartment">新增</a-button>
          </div>
        </a-form-item>

        <a-form-item label="所属节点" name="parentNode">
          <div class="select-with-add">
            <a-select
              v-model:value="formData.parentNode"
              placeholder="请选择所属节点"
              size="large"
              show-search
              :options="parentNodeOptions"
              style="flex: 1"
            />
            <a-button @click="showAddParentNode">新增</a-button>
          </div>
        </a-form-item>

        <a-form-item label="支联管理员" name="manager" required>
          <div class="select-with-add">
            <a-select
              v-model:value="formData.manager"
              placeholder="请选择支联管理员"
              size="large"
              show-search
              :options="managerOptions"
              style="flex: 1"
            />
            <a-button @click="showAddManager">新增</a-button>
          </div>
        </a-form-item>

        <a-form-item label="联系电话" name="contactPhone">
          <a-input
            v-model:value="formData.contactPhone"
            placeholder="请输入联系电话"
            size="large"
          />
        </a-form-item>

        <a-form-item label="邮箱地址" name="email">
          <a-input
            v-model:value="formData.email"
            placeholder="请输入邮箱地址"
            size="large"
          />
        </a-form-item>

        <a-form-item label="备注信息" name="remark">
          <a-textarea
            v-model:value="formData.remark"
            placeholder="请输入备注信息"
            :rows="3"
            size="large"
          />
        </a-form-item>

        <!-- 操作按钮 -->
        <a-form-item class="form-actions">
          <a-space size="large">
            <a-button size="large" @click="goBack">取消</a-button>
            <a-button
              type="primary"
              size="large"
              :loading="submitLoading"
              @click="handleSubmit"
            >
              {{ isEditMode ? "保存修改" : "确定" }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message, Modal } from "ant-design-vue";

const router = useRouter();
const route = useRoute();
const formRef = ref();
const submitLoading = ref(false);
const isEditMode = ref(false);
const editId = ref<string | null>(null);

// 表单数据
const formData = reactive({
  nodeName: "",
  nodeType: "",
  department: "",
  parentNode: "",
  manager: "",
  contactPhone: "",
  email: "",
  remark: "",
});

// 表单验证规则
const formRules = {
  nodeName: [
    { required: true, message: "请输入节点名称", trigger: "blur" },
    { max: 20, message: "节点名称不能超过20个字符", trigger: "blur" },
  ],
  nodeType: [{ required: true, message: "请选择节点类型", trigger: "change" }],
  manager: [{ required: true, message: "请选择支联管理员", trigger: "change" }],
  email: [{ type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }],
  contactPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
};

// 选项数据
const nodeTypeOptions = [
  { label: "集团级", value: "集团级" },
  { label: "省市级", value: "省市级" },
  { label: "区县级", value: "区县级" },
];

const departmentOptions = [
  { label: "哈尔滨工业大学", value: "哈尔滨工业大学" },
  { label: "清华大学", value: "清华大学" },
  { label: "北京大学", value: "北京大学" },
];

const parentNodeOptions = [
  { label: "L1_JW_BJ_12345", value: "L1_JW_BJ_12345" },
  { label: "L1_JW_SH_67890", value: "L1_JW_SH_67890" },
];

const managerOptions = [
  { label: "陆长河", value: "陆长河" },
  { label: "张三", value: "张三" },
  { label: "李四", value: "李四" },
];

// 检查表单是否有数据
const hasFormData = () => {
  return Object.values(formData).some(
    (value) => value && value.toString().trim()
  );
};

// 返回上一页
const goBack = () => {
  if (hasFormData()) {
    Modal.confirm({
      title: "确认离开？",
      content: "您有未保存的数据，确定要离开吗？",
      okText: "确定离开",
      cancelText: "继续编辑",
      onOk() {
        router.back();
      },
    });
  } else {
    router.back();
  }
};

// 跳转到节点管理页面
const goToNodeManagement = () => {
  router.push("/node-management");
};

// 新增按钮方法
const showAddDepartment = () => {
  message.info("新增");
};
const showAddParentNode = () => {
  message.info("新增");
};
const showAddManager = () => {
  message.info("新增");
};

// 初始化编辑数据
const initEditData = () => {
  const query = route.query;
  if (query.mode === "edit") {
    isEditMode.value = true;
    editId.value =
      typeof query.id === "string"
        ? query.id
        : Array.isArray(query.id)
        ? query.id[0]
        : null;

    // 回显数据，注意类型转换
    formData.nodeName =
      typeof query.nodeName === "string" ? query.nodeName : "";
    formData.nodeType =
      typeof query.nodeType === "string" ? query.nodeType : "";
    formData.department =
      typeof query.department === "string" ? query.department : "";
    formData.parentNode =
      typeof query.parentNode === "string" ? query.parentNode : "";
    formData.manager = typeof query.manager === "string" ? query.manager : "";
    formData.contactPhone =
      typeof query.contactPhone === "string" ? query.contactPhone : "";
    formData.email = typeof query.email === "string" ? query.email : "";
    formData.remark = typeof query.remark === "string" ? query.remark : "";
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitLoading.value = true;
    const submitData = {
      ...formData,
      id: isEditMode.value ? editId.value : Date.now(),
    };
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success(isEditMode.value ? "节点修改成功！" : "节点创建成功！");
    setTimeout(() => {
      router.push("/node-management");
    }, 800);
  } catch (error) {
    message.error("请检查表单信息");
  } finally {
    submitLoading.value = false;
  }
};

onMounted(() => {
  initEditData();
});
</script>

<style scoped lang="less">
.custom-header {
  display: flex;
  align-items: center;
  height: 48px;
  background: #fff;
  padding-left: 16px;
  font-size: 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 0;
}
.back-area {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  font-size: 16px;
  color: #8c8c8c;
  transition: color 0.2s;
  padding: 0 4px 0 0;
}
.back-area:hover .back-text,
.back-area:hover .back-icon {
  color: #1890ff;
  stroke: #1890ff;
}
.back-icon {
  display: inline-block;
  vertical-align: middle;
  margin-right: 2px;
  color: #bfbfbf;
  stroke: #bfbfbf;
  transition: stroke 0.2s;
}
.back-text {
  font-size: 16px;
  color: #595959;
  margin-right: 8px;
  transition: color 0.2s;
}
.header-divider {
  color: #d9d9d9;
  font-size: 18px;
  margin: 0 12px 0 0;
  font-weight: 400;
  user-select: none;
}
.header-title {
  font-size: 18px;
  font-weight: 500;
  color: #262626;
  letter-spacing: 1px;
  margin-top: 1px;
}
.node-create {
  padding: 24px;
  background: #f0f2f5;
}
.form-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  :deep(.ant-card-body) {
    padding: 24px;
  }
}
.select-with-add {
  display: flex;
  align-items: center;
  gap: 8px;
}
:deep(.ant-form-item) {
  width: 50%;
  &.form-actions {
    width: 100%;
  }
}
:deep(.form-actions) {
  margin-top: 32px;
  margin-bottom: 0;
  text-align: center;
  .ant-form-item-control-input-content {
    display: flex;
    justify-content: center;
  }
}
:deep(.ant-form-item-label) {
  font-weight: 500;
  .ant-form-item-required::before {
    color: #ff4d4f;
  }
}
:deep(.ant-input),
:deep(.ant-select-selector),
:deep(.ant-input-number) {
  border-radius: 6px;
  &:hover {
    border-color: #40a9ff;
  }
  &:focus,
  &.ant-input-focused,
  &.ant-select-focused .ant-select-selector {
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }
}
:deep(.ant-btn) {
  border-radius: 6px;
  font-weight: 500;
  &.ant-btn-primary {
    background: #1890ff;
    border-color: #1890ff;
    &:hover {
      background: #40a9ff;
      border-color: #40a9ff;
    }
  }
}
.select-with-add {
  .ant-btn {
    color: #1890ff;
    border-color: #1890ff;
    background: transparent;
    &:hover {
      color: #40a9ff;
      border-color: #40a9ff;
      background: #f0f8ff;
    }
    &:focus {
      color: #1890ff;
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }
}
@media (max-width: 768px) {
  .form-card {
    :deep(.ant-card-body) {
      padding: 16px;
    }
  }
  :deep(.ant-form-item) {
    width: 100%;
  }
}
</style>
